package com.example.allshengmedical.system.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import junit.runner.Version;

import android.R.integer;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.os.Message;

import com.allsheng.widget.AllShengDialog;
import com.allsheng.widget.AllShengDialog.ClickListenerInterface;
import com.allsheng.widget.UpdateDialog;
import com.allsheng.widget.UpdateDialog.UpdateClickListenerInterface;
import com.example.allshengmedical.R;
import com.example.allshengmedical.base.BaseActivity;
import com.example.allshengmedical.mainmenu.activity.MainMenuActivity;
import com.example.allshengmedical.system.presenter.MaintenancePresenter;
import com.example.allshengmedical.system.view.IMaintenanceView;
import com.example.allshengmedical.util.ByAlert;
import com.itboye.allshengmedical.sci.DefaultSerialControl;
import com.itboye.allshengmedical.sci.ISerialControl;
import com.itboye.allshengmedical.sci.SerialPort;
import com.itboye.allshengmedical.sci.cmd.req.CmdType;
import com.itboye.allshengmedical.sci.packet.resp.BaseRespPacket;
import com.itboye.allshengmedical.sci.packet.resp.UpdateRespPacket;
import com.itboye.allshengmedical.sci.packet.resp.VersionRespPacket;

public class MaintenanceActivity extends BaseActivity implements
		IMaintenanceView, OnClickListener {

	private Button updateBtn, poiBtn, bgCalibrationBtn, opticalBtn, dyeBtn,
			otherBtn;
	private MaintenancePresenter maintenancePresenter;
	String update = "";
	ISerialControl controlInstance;
	private OutputStream mOutputStream;
	SCMUpdate scmUpdate = new SCMUpdate();
	private final static String FILEPATH = "/mnt/udisk/Gene32.bin";
	private final static String fileName = "mnt/udisk/";
	private final static String HaveUDisk = "/proc/partitions";
	int checkSum;// 校验位
	String version;
	ProgressDialog progressDialog;
	private Dialog myDialog;
	boolean isShow = false;

	@Override
	protected int setcontent() {
		return R.layout.activity_system_maintenance;
	}

	@Override
	protected void initView() {
		maintenancePresenter = new MaintenancePresenter(this);
		maintenancePresenter.initAppHead();
		progressDialog = new ProgressDialog(MaintenanceActivity.this);
	}

	@Override
	protected void initData() {
		controlInstance = DefaultSerialControl.getInstance();
		controlInstance.init();
		controlInstance.start();
		controlInstance.setHandler(handler);
		controlInstance.addCommand(CmdType.Version, "", 0);
	}

	@Override
	public void initAppHead() {
		setSystemTime();
		setActionBar();

	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case ISerialControl.FindPacketMessage:
				updateMsg(msg.getData());
				break;
			case ISerialControl.SCTimeoutMessage:
				if (isShow) {
					try {
						closeProgressDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					final AllShengDialog allShengDialog = new AllShengDialog(
							MaintenanceActivity.this, "", "更新请求超时,请重试", "ok");
					allShengDialog.show();
					allShengDialog
							.setClicklistener(new ClickListenerInterface() {

								@Override
								public void OK() {
									// TODO Auto-generated method stub
									allShengDialog.dismiss();
								}

								@Override
								public void Cancle() {
									// TODO Auto-generated method stub
									allShengDialog.dismiss();

								}
							});
				}
				break;
			default:
				break;
			}

		}

		private void updateMsg(Bundle msg) {
			// TODO Auto-generated method stub
			String cmdType = msg.getString("cmdType");
			BaseRespPacket packet = (BaseRespPacket) msg
					.getSerializable("packet");
			if (cmdType.length() < 1)
				return;
			// 根据type 转换packet 为你想要的
			CmdType type = CmdType.getCmdType(cmdType.substring(1));
			// 发送指令后这里会收到数据
			Log.d("read_data", "接受到的响应数据包是" + cmdType + type.toDesc());
			switch (type) {
			case Version:
				VersionRespPacket versionpacket = new VersionRespPacket(packet);
				version = versionpacket.getVersion() + ",时间："
						+ versionpacket.getTime();
				break;
			case UpdateArm:

				UpdateRespPacket updatePacket = new UpdateRespPacket(packet);
				if ("end".equals(updatePacket.isEnd())) {
					try {
						closeProgressDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					// ByAlert.alert("更新失败");
					// if (null != myDialog && myDialog.isShowing()) { //
					// Log.e("wenqg",
					// // "myDialog.isShowing() print!");
					// myDialog.dismiss();
					// System.gc();
					// }
					final AllShengDialog allShengDialog = new AllShengDialog(
							MaintenanceActivity.this, "", "更新失败", "ok");
					allShengDialog.show();
					allShengDialog
							.setClicklistener(new ClickListenerInterface() {

								@Override
								public void OK() {
									// TODO Auto-generated method stub
									allShengDialog.dismiss();
								}

								@Override
								public void Cancle() {
									// TODO Auto-generated method stub
									allShengDialog.dismiss();

								}
							});
				} else if ("success".equals(updatePacket.isEnd())) {
					try {
						closeProgressDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					// ByAlert.alert("更新成功");
					final AllShengDialog allShengDialog = new AllShengDialog(
							MaintenanceActivity.this, "", "更新成功", "ok");
					allShengDialog.show();
					allShengDialog
							.setClicklistener(new ClickListenerInterface() {

								@Override
								public void OK() {
									// TODO Auto-generated method stub
									allShengDialog.dismiss();
								}

								@Override
								public void Cancle() {
									// TODO Auto-generated method stub
									allShengDialog.dismiss();

								}
							});
				} else {
					try {
						Thread thread = new Thread(runnable);
						thread.start();
					} catch (Exception e) {
						// TODO: handle exception
					}

				}
				break;
			}
		};
	};

	@Override
	public void upDateFunction() {
		if (SCMUpdate.isHaveUDisk()) {
			// } else {
			// ByAlert.alert("没有U盘");
			// }、
			if (version != null) {
				final UpdateDialog dialog = new UpdateDialog(
						MaintenanceActivity.this, "单片机升级，当前版本:V" + version);
				dialog.show();
				update = null;
				dialog.setClicklistener(new UpdateClickListenerInterface() {

					@Override
					public void OK() {
						// TODO Auto-generated method stub
						if ("SCMUpdate".equals(update)) {

							if (null != SCMUpdate.isHaveFile()) {
								isShow = true;
								showProgressDialog("更新中...", true);
								controlInstance.addCommand(CmdType.UpdateArm,
										"start", upgradeMCUNum());
							} else {
								ByAlert.alert(getString(R.string.system_cantfind));
							}
							dialog.dismiss();

						} else if ("AppUpdate".equals(update)) {
							// if (SCMUpdate.isHaveUDisk()) {
							SCMUpdate.UpdateMainApp(MaintenanceActivity.this);
							// dialog.dismiss();
							// } else {
							// ByAlert.alert("没有U盘");
							// }
						} else {
							ByAlert.alert(getString(R.string.system_chosetype));
						}

					}

					@Override
					public void Cancle() {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}

					@Override
					public void AppUpdate() {
						// TODO Auto-generated method stub
						update = "AppUpdate";
					}

					@Override
					public void SCMUpdate() {
						// TODO Auto-generated method stub
						update = "SCMUpdate";
					}
				});
			} else {
				final AllShengDialog allShengDialog = new AllShengDialog(
						MaintenanceActivity.this, "", "指令失败", "ok");
				allShengDialog.show();
				allShengDialog.setClicklistener(new ClickListenerInterface() {

					@Override
					public void OK() {
						allShengDialog.dismiss();
					}

					@Override
					public void Cancle() {
						// TODO Auto-generated method stub
						allShengDialog.dismiss();

					}
				});

			}
		} else {
			ByAlert.alert("没有U盘");
		}
	}

	@Override
	public void poiFunction() {
		ByAlert.alert("2");

	}

	@Override
	public void backgroundFunction() {
		ByAlert.alert("3");

	}

	@Override
	public void opticalFunction() {
		// ByAlert.alert("4");
		Intent intent = new Intent(MaintenanceActivity.this,
				OpticalActivity.class);
		startActivity(intent);
	}

	@Override
	public void dyeFunction() {
		ByAlert.alert("5");

	}

	@Override
	public void otherFunction() {
		Intent intent = new Intent(MaintenanceActivity.this,
				OtherActivity.class);
		startActivity(intent);
		finish();

	}

	// 获取当前时间的方法
	public void setSystemTime() {

		TextView date, fileName;
		date = BindView(R.id.date);
		fileName = BindView(R.id.file_name);

		// 获取系统时间
		SimpleDateFormat sdfDate = new SimpleDateFormat("MM dd,yyyy");
		date.setText(sdfDate.format(new Date()));

		// 文件路径置空
		fileName.setText("");

	}

	// 设置actionBar
	public void setActionBar() {
		Button leftfirstBtn, leftsecondBtn;
		TextView title;

		leftfirstBtn = BindView(R.id.leftfirst_btn);
		leftsecondBtn = BindView(R.id.leftsecond_btn);
		title = BindView(R.id.title);

		leftfirstBtn.setVisibility(View.VISIBLE);
		leftfirstBtn.setText(R.string.item_actionbar_back);
		leftsecondBtn.setVisibility(View.VISIBLE);
		leftsecondBtn.setText(R.string.item_actionbar_home);
		title.setText(R.string.systemActivity_maintenance);

		leftfirstBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MaintenanceActivity.this,
						SystemActivity.class);
				startActivity(intent);
				finish();

			}
		});
		leftsecondBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MaintenanceActivity.this,
						MainMenuActivity.class);
				startActivity(intent);
				finish();
			}
		});

	}

	Runnable runnable = (new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				int fileLen = upgradeMCUNum();
				int startset = 0;
				while (fileLen > 0) {
					if (fileLen >= 1024) {
						sendUpgradesData(update(), startset, 1024);
						fileLen -= 1024;
						startset += 1024;
					} else {
						sendUpgradesData(update(), startset, fileLen);
						startset += fileLen;
						fileLen = 0;
					}
					SystemClock.sleep(300);
					if (startset >= upgradeMCUNum()) {
						controlInstance.addCommand(CmdType.UpdateArm, "end",
								checkSum);

					}
				}

			} catch (Exception e) {
				// TODO: handle exception
				Looper.prepare();
				ByAlert.alert(getString(R.string.system_uperror));
				Looper.loop();
			}
		}

	});

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.updateBtn:
			maintenancePresenter.upDateFunction();
			break;
		case R.id.poiBtn:
			maintenancePresenter.poiFunction();
			break;
		case R.id.bgCalibrationBtn:
			maintenancePresenter.backgroundFunction();
			break;
		case R.id.opticalBtn:
			maintenancePresenter.opticalFunction();
			break;
		case R.id.dyeBtn:
			maintenancePresenter.dyeFunction();
			break;
		case R.id.otherBtn:
			maintenancePresenter.otherFunction();
			break;

		default:
			break;
		}
	}

	public void sendUpgradesData(byte data1[], int startset, int len) {
		if (len <= 0) {
			return;
		}
		byte data[] = new byte[len];
		System.arraycopy(data1, startset, data, 0, len);
		controlInstance.sendCmd(data);

	}

	public byte[] update() {
		String result = null;
		int fileLen = 0;
		byte[] upgradeData = new byte[65536];
		File f1 = new File(FILEPATH);
		if (f1.exists()) {
			FileInputStream inStream = null;
			long s = 0;
			try {
				inStream = new FileInputStream(f1);
				s = inStream.available();
				s = (s / 32 + 1) * 32;
				byte buffer[] = new byte[(int) s];
				int len = 0;
				ByteArrayOutputStream ostream = new ByteArrayOutputStream();
				while ((len = inStream.read(buffer)) != -1) {
					ostream.write(buffer, 0, len);

				}
				inStream.close();
				upgradeData = ostream.toByteArray();
				result = upgradeData.toString();
				fileLen = upgradeData.length;
				int offset = 0;
				// sendStartUpgradesCmd(fileLen);
				checkSum = 0;
				for (int i = 0; i < fileLen; i++) {
					if (upgradeData[i] >= 0) {
						checkSum += upgradeData[i];
					} else {
						checkSum += (upgradeData[i] + 256);
					}
				}
				ostream.close();
			} catch (IOException e) {
				ByAlert.alert(getString(R.string.system_uperror));
			}

		} else {
			ByAlert.alert(getString(R.string.system_nofile));
		}
		return upgradeData;
	}

	public int upgradeMCUNum() {
		String result = null;
		int fileLen = 0;
		byte[] upgradeData = new byte[65536];
		File f1 = new File(FILEPATH);
		if (f1.exists()) {
			FileInputStream inStream = null;
			long s = 0;
			try {
				inStream = new FileInputStream(f1);
				s = inStream.available();
				s = (s / 32 + 1) * 32;
				byte buffer[] = new byte[(int) s];
				int len = 0;
				ByteArrayOutputStream ostream = new ByteArrayOutputStream();
				while ((len = inStream.read(buffer)) != -1) {
					ostream.write(buffer, 0, len);

				}
				inStream.close();
				upgradeData = ostream.toByteArray();
				result = upgradeData.toString();
				fileLen = upgradeData.length;
				ostream.close();
			} catch (IOException e) {
			}

		} else {
		}
		// Log.e("hu.fil", fileLen + "");
		return (fileLen);
	}

	private void DialogShow() {
		if (null != myDialog && myDialog.isShowing()) { // Log.e("wenqg",
														// "myDialog.isShowing() print!");
			myDialog.dismiss();
			System.gc();
		}

		LayoutInflater layoutInflater1 = getLayoutInflater();
		View tv_tmp = layoutInflater1.inflate(R.layout.simple_textview, null);
		TextView tmp = (TextView) tv_tmp.findViewById(R.id.simple_tv);
		tmp.setText("更新中...");
		tmp.setTextColor(Color.BLACK);

		myDialog = new Dialog(MaintenanceActivity.this);
		myDialog.setContentView(tv_tmp);
		myDialog.setCancelable(false);

		Window dialogWindow = myDialog.getWindow();
		dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
		WindowManager.LayoutParams params = dialogWindow.getAttributes();
		params.x = 300;
		params.y = 150;
		params.width = LayoutParams.WRAP_CONTENT;
		params.height = LayoutParams.WRAP_CONTENT;
		dialogWindow.setAttributes(params);

		myDialog.show();
	}

}
